<template>
  <div class="app-container">

    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-form :inline="true">
        <el-form-item label="帐号名称">
          <el-input v-model="listQuery.username" type="text" clearable placeholder="帐号名称"/>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="listQuery.dataStatus" placeholder="请选择">
            <el-option
              v-for="item in status_options"
              :key="item.value"
              :label="item.label"
              :value="item.value"/>
          </el-select>
        </el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleFilter">查找</el-button>
        <el-button
          v-hasPermi="['admin:sys:user:create']"
          style="float:right"
          type="primary"
          icon="el-icon-plus"
          @click="startAdd">添加</el-button>
      </el-form>
    </div>

    <!-- 查询结果 -->
    <el-table v-loading="listLoading" :data="list" element-loading-text="正在查询中。。。" border fit highlight-current-row >

      <el-table-column align="center" label="帐号名称" prop="username" />

      <el-table-column align="center" label="所属部门" prop="sysDept"/>
      <el-table-column align="center" label="手机号码" prop="phoneNumber"/>

      <el-table-column align="center" label="状态" prop="dataStatus" >
        <template v-hasPermi="['admin:sys:user:updateStatus']" slot-scope="{row}">
          <div v-if="row.superAdminFlag != 1">
            <el-switch
              :active-value="1"
              :inactive-value="2"
              v-model="row.dataStatus"
              @change="handleStatusChange(row)"/>
          </div>
          <div v-else>{{ row.dataStatusStr }}</div>
        </template>

      </el-table-column>
      <el-table-column align="center" label="创建时间" prop="createTime"/>

      <el-table-column align="center" label="操作" width="180" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button
            v-hasPermi="['admin:sys:user:update']"
            v-if="row.superAdminFlag != 1"
            type="primary"
            size="small"
            @click="startEditAdmin(row)">编辑</el-button>
            <el-button type="primary" size="small"
            v-hasPermi="['admin:sys:user:resetPassword']"
            v-if="row.superAdminFlag != 1"
            @click="chongzhiAdminFunc(row)">重置密码</el-button>
            <!-- <el-button type="primary" size="small"
          v-hasPermi="['admin:sys:user:delete']"
          @click="deleteAdminFunc(scope.row.username, scope.row.id)">删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.pageSize" @pagination="getList" />

    <el-dialog :close-on-click-modal="false" :title="dialogType === 1?'新增账号':'修改账号'" :visible.sync="dialogFormVisible" width="28%">
      <el-form ref="dialogForm" :rules="formRules1" :model="dialogForm" label-width="120px">

        <el-form-item label="帐号名称" prop="username">
          <el-input v-model="dialogForm.username" type="text" clearable placeholder="帐号名称"/>
        </el-form-item>
        <el-form-item label="所属部门" prop="sysDeptId">
          <treeselect
            v-model="dialogForm.sysDeptId"
            :normalizer="normalizer"
            :options="deptList"
            :show-count="true"
            placeholder="请选择归属部门"/>
        </el-form-item>
        <el-form-item v-if="!dialogForm.id" :prop="dialogForm.id ? '' : 'password'" label="密码">
          <el-input v-model="dialogForm.password" type="password" show-password clearable placeholder=""/>
        </el-form-item>
        <el-form-item v-if="!dialogForm.id" :prop="dialogForm.id ? '' : 'qrPassword'" label="确认密码">
          <el-input v-model="dialogForm.qrPassword" type="password" show-password clearable placeholder=""/>
        </el-form-item>
        <el-form-item label="手机号码" prop="phoneNumber">
          <el-input v-model="dialogForm.phoneNumber" clearable placeholder=""/>
        </el-form-item>
        <el-form-item label="角色配置" prop="roleIdList">
          <el-select v-model="dialogForm.roleIdList" multiple placeholder="请选择" style="width:100%;">
            <el-option
              v-for="item in roleList"
              :key="item.id"
              :label="item.name"
              :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="dataStatus">
          <el-radio-group v-model="dialogForm.dataStatus">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="2">停用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer" align="center">
        <el-button @click="confirmEdit('dialogForm')">确定</el-button>
        <el-button @click="dialogFormVisible = false">取消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
/* eslint-disable eqeqeq */

import { listUser, createUser, detailUser, updateUser, updateUserStatus, listUserRole,
  listUserDept,resetPassword } from '@/api/permission/user'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { getData, } from '@/api/system/dictionary'
export default {
  name: 'Admin',
  components: { Pagination, Treeselect },
  data() {
    return {
      list: null,
      total: 0,
      listLoading: true,
      status_options: [],
      normalizer(node) { // 方法
        return {
          id: node.id, // 键名转换，方法默认是label和children进行树状渲染
          label: node.name,
          children: node.children
        }
      },
      listQuery: {
        page: 1,
        pageSize: 20
      },
      downloadLoading: false,
      dialogFormVisible: false,
      dialogForm: {
        username: ''
      },
      dialogType: 1,
      formRules: {
        username: [
          { required: true, message: '用户名称不能为空', trigger: 'blur' },
          { min: 2, max: 20, message: '用户名称长度必须介于 2 和 20 之间', trigger: 'blur' }
        ],
        sysDeptId: [
          { required: true, message: '所属部门不能为空', trigger: 'change' }
        ],
        phoneNumber: [
          { required: true, message: '手机号码不能为空', trigger: 'blur' }
        ],
        roleIdList: [
          { required: true, message: '角色配置不能为空', trigger: 'change' }
        ],
        dataStatus: [
          { required: true, message: '状态不能为空', trigger: 'change' }
        ]
      },
      formRules1: {},
      roleList: [], // 角色数据
      deptList: []// 部门数据
    }
  },
  created() {
    this.listUserRole()
    this.listUserDept()
    this.getList()
		this.getData()
  },
  methods: {
		async getData(){//设备状态
			let res = await getData('EDataStatus')
			let list = res.data || []
			this.status_options = [{
        value: '',
        label: '全部'
      },...list]
		},
    // 用户状态修改
    handleStatusChange(row) {
      const text = row.dataStatus == 1 ? '启用' : '停用'
      this.$confirm('确认要"' + text + '""' + row.username + '"用户吗？', '温馨提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        updateUserStatus({ id: row.id, dataStatus: row.dataStatus }).then(response => {
          this.$message({
            message: text + '成功',
            type: 'success'
          })
          this.getList()
        })
      }).catch(() => {
        row.dataStatus = row.dataStatus == 2 ? 1 : 2
      })
    },
    listUserRole() { // 用户可授权的角色
      listUserRole().then(response => {
        const list = response.data || []
        this.roleList = list
      })
    },
    listUserDept() { // 用户可授权的部门
      listUserDept().then(response => {
        const list = response.data || []
        this.deptList = list
      })
    },
    reset() {
      this.dialogForm = {
        username: '',
        sysDeptId: null,
        password: '',
        qrPassword: '',
        phoneNumber: '',
        roleIdList: '',
        dataStatus: 1
      }
    },
    getList() {
      this.listLoading = true
      listUser(this.listQuery).then(response => {
        const data1 = response.data || {}
        const list = data1.list || []
        this.list = list
        this.total = data1.total || 0
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    deleteAdminFunc(username, adminId) {
      this.$confirm(`您确定删除账号：${username}`, '温馨提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteAdmin({ id: adminId }).then(response => {
          this.$message({
            message: '删除成功!',
            type: 'success'
          })
          this.getList()
        })
      })
    },
    startAdd() {
      this.formRules1 = {
        ...this.formRules,
        password: [
          { required: true, message: '用户密码不能为空', trigger: 'blur' },
          { min: 5, max: 20, message: '用户密码长度必须介于 5 和 20 之间', trigger: 'blur' }
        ],
        qrPassword: [
          { required: true, message: '用户密码不能为空', trigger: 'blur' },
          { min: 5, max: 20, message: '用户密码长度必须介于 5 和 20 之间', trigger: 'blur' }
        ]
      }
      this.reset()
      this.dialogFormVisible = true
      this.dialogType = 1
      this.$nextTick(() => {
        this.$refs['dialogForm'].resetFields()
      })
    },

    confirmEdit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.dialogForm.password && this.dialogForm.password !== this.dialogForm.qrPassword) {
            this.$message({
              message: '密码和确认密码要一致',
              type: 'warning'
            })
            return
          }
          if (this.dialogType == 1) {
            createUser(this.dialogForm).then(response => {
              this.$message({
                message: '添加成功!',
                type: 'success'
              })
              this.getList()
              this.dialogFormVisible = false
              this.dialogForm = {}
            })
          } else {
            updateUser(this.dialogForm).then(response => {
              this.$message({
                message: '修改成功!',
                type: 'success'
              })
              this.getList()
              this.dialogFormVisible = false
              this.dialogForm = {}
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    chongzhiAdminFunc(row){//重置密码
      this.$confirm(`您确定将账号：${row.username}密码重置为123456`, '温馨提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        resetPassword({ id: row.id }).then(response => {
          this.$message({
            message: '操作成功!',
            type: 'success'
          })
          this.getList()
        })
      })
    },
    startEditAdmin(row) {
      this.reset()
      this.formRules1 = {
        ...this.formRules

      }
      detailUser(row.id).then(async response => {
        const data1 = response.data || {}
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dialogForm'].resetFields()
          this.dialogType = 2
          this.dialogForm = data1 || {}
        })
      })
    }

  }

}
</script>
